import React from 'react';
import styles from './index.less';
import { Modal, Button, Checkbox, Tree } from 'antd';
import TBasePage from '#/base/TBasePage';
import { CloseOutlined } from '#/utils/antdIcons';
import TRNotification from '#/utils/notification';
import plan_icon from '@/assets/img/plan_icon.png';
import _ from 'lodash';

const { TreeNode } = Tree;

const convertTreeToArray = (data, treeMap = [], depth = 0) => {
  let lintDepth = depth;
  if (!(data && data.length)) return [];
  lintDepth++;
  return data.reduce((acc, cur) => {
    cur.depth = lintDepth;
    acc.push(cur);
    if (cur.children && cur.children.length) {
      convertTreeToArray(cur.children, treeMap, lintDepth);
    }
    if (cur.secondMenuList && cur.secondMenuList.length) {
      convertTreeToArray(cur.secondMenuList, treeMap, lintDepth);
    }
    return acc;
  }, treeMap);
};

class PopupSettleComponent extends TBasePage {
  static defaultProps = {
    data: [],
    expandData: [],
    stationData: [],
  };
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      treeData: [],
      stationData: [],
      expandTreeData: [],
      checkTreeData: [],
      treeDataList: [],
      personList: [], //右侧列表
    };
  }

  mapArr = (arr) => {
    const { names } = this.props;
    let array = [];
    if (names === 'jingying') {
      array = arr && arr.filter((item) => item.label === '区域');
    } else {
      array = arr && arr.filter((item) => item.label === '项目');
    }
    return array;
  };
  componentDidMount() {
    const { expandData, stationData } = this.props;
    let stationDatas = this.mapArr(convertTreeToArray(stationData));
    let treeList = convertTreeToArray(this.props.data);
    let stationList = this.mapArr(convertTreeToArray(this.props.data));
    let defindArr =
      stationDatas.length == stationList.length
        ? treeList.map((item) => item.deptNum)
        : stationDatas.map((item) => item.deptNum); //左面数组默认显示
    this.setState(
      {
        visible: true,
        treeData: this.props.data,
        personList: this.mapArr(convertTreeToArray(stationData)) || [], //右边数组
        expandTreeData: expandData, //展开节点
        checkTreeData: defindArr,
        treeDataList: treeList, //全选
        stationData: stationList,
      },
      () => {},
    );
  }

  _onCancel = () => {
    const { onPress } = this.props;
    this.setState(
      {
        visible: false,
      },
      () => {
        onPress({ index: 0 });
      },
    );
  };
  _onOk = () => {
    const { personList, expandTreeData } = this.state;
    const { onPress } = this.props;
    this.setState(
      {
        visible: false,
      },
      () => {
        onPress({ index: 1, expandList: expandTreeData, stationList: personList });
      },
    );
  };
  _onSelClear() {
    //清空
    this._onTreeChange(true);
  }
  _onTreeChange(isAll) {
    const { treeDataList, stationData } = this.state;
    this.setState({
      checkTreeData: isAll ? [] : treeDataList.map((item) => item.deptNum),
      personList: isAll ? [] : [...stationData],
    });
  }

  _onTreeCheck(checkedKeys) {
    //树状图单选变化
    const { stationData } = this.state;
    // let array=treeDataList.map(item=>item.deptNum)
    // let treeDataLists=array.filter(n=>checkedKeys.includes(n));

    this.setState({
      checkTreeData: checkedKeys,
      personList: stationData.filter((n) => checkedKeys.indexOf(n.deptNum) >= 0),
    });
  }

  _onTreeExpand(expandedKeys) {
    this.setState({
      expandTreeData: expandedKeys,
    });
  }
  appIds = (treeData, arr) => {
    return treeData.map((n) => {
      let child = this.appIds(n.children, [...arr, n.deptId]);
      return { ...n, link: [...arr, n.deptId], children: child };
    });
  };
  filterTreeDataByIds = (treeData, keys = []) => {
    //向上查找父节点
    let arr = [];
    const flatArray = convertTreeToArray(this.appIds(treeData, []));
    const checkArray = flatArray.filter((n) => keys.includes(n.deptNum));
    const allDepts = _.union(_.flatten(checkArray.map((n) => n.link)));
    const filterArray = flatArray.filter((n) => allDepts.includes(n.deptId));
    arr.push(filterArray);
    return arr.flat();
  };

  _onSelChange(item) {
    //右侧单个删除
    const { personList, checkTreeData } = this.state;
    const newPlist = personList.filter((n) => String(n.deptNum) !== String(item.deptNum));
    let deptNumArr = this.filterTreeDataByIds(this.props.data, item.deptNum).map(
      (item) => item.deptNum,
    );

    this.setState({
      checkTreeData: checkTreeData.filter((n) => {
        return !deptNumArr.includes(n);
      }),
      personList: newPlist,
    });
  }
  _onRenderTreeNodes(data) {
    const { names } = this.props;
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode
            title={names == 'jingying' ? item.region : item.deptName}
            key={item.deptNum}
            dataRef={item}
          >
            {this._onRenderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.deptNum} {...item} />;
    });
  }
  render() {
    const { checkTreeData, treeData, expandTreeData, treeDataList, personList } = this.state;
    const { names, block } = this.props;
    let treeCheckOptions = {};
    if (checkTreeData.length > 0 && checkTreeData.length != treeDataList.length) {
      treeCheckOptions.indeterminate = true;
    }
    const treeCheck = checkTreeData.length > 0 && checkTreeData.length == treeDataList.length;
    return (
      <Modal
        width={540}
        centered
        closable={false}
        className="modalWraps"
        maskClosable={false}
        visible={this.state.visible}
        footer={[
          <Button key="dtest1" onClick={this._onCancel.bind(this)}>
            取消
          </Button>,
          personList.length > 0 ? (
            <Button key="dtest2" onClick={this._onOk.bind(this)} type="primary">
              提交
            </Button>
          ) : (
            <Button key="dtest2" disabled>
              提交
            </Button>
          ),
        ]}
        wrapClassName={block ? styles.rmodalBlock : ''}
        onCancel={this._onCancel.bind(this)}
      >
        <div className={styles.rmodal}>
          <div className={styles.PopupTitle}>
            <div className={styles.popright}>
              <span>
                <img src={plan_icon} alt="" />
              </span>
              <b style={{ color: block ? '#fff' : '#373E48' }}>中心</b>
            </div>
            <span className="clons">
              <CloseOutlined
                className={styles.close}
                style={{ fontSize: '18px' }}
                onClick={this._onCancel.bind(this)}
              />
            </span>
          </div>
          <div className={styles.card}>
            <div className={styles.container}>
              <div className={styles.treebox}>
                <div style={{ marginBottom: '8px' }}>
                  <Checkbox
                    checked={treeCheck}
                    {...treeCheckOptions}
                    onChange={this._onTreeChange.bind(this, treeCheck)}
                  >
                    全选
                  </Checkbox>
                </div>
                <Tree
                  checkable
                  expandedKeys={expandTreeData}
                  onExpand={this._onTreeExpand.bind(this)}
                  checkedKeys={checkTreeData}
                  onCheck={this._onTreeCheck.bind(this)}
                  ref={(node) => (this.tree = node)}
                  className="trees"
                >
                  {this._onRenderTreeNodes(treeData)}
                </Tree>
              </div>
              <div className={styles.searchbox}>
                <div className={styles.colr}>
                  <div>{`已选${personList.length}项`}</div>
                  <div onClick={this._onSelClear.bind(this)} className={styles.clear}>
                    清空
                  </div>
                </div>

                {personList.map((item) => {
                  return (
                    <div
                      key={item.deptNum}
                      className={`${styles.rightBoxItem} ${block ? styles.rightBoxItemBlock : ''}`}
                    >
                      <CloseOutlined
                        className={styles.close}
                        onClick={this._onSelChange.bind(this, item)}
                      />
                      {names == 'jingying' ? (
                        <div className={styles.rightName}>{item.region}</div>
                      ) : (
                        <div className={styles.rightName}>{item.deptName}</div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </Modal>
    );
  }
}

class PopupSettleModal {
  __key__ = '';
  show = (data, expandData, stationData, names, block) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') {
        return;
      }
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <PopupSettleComponent
            data={data}
            stationData={stationData}
            expandData={expandData}
            names={names}
            block={block}
            onPress={(obj) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(obj);
            }}
          />
        ),
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

const CentreModal = new PopupSettleModal();
export default CentreModal;
